package org.jeecg.modules.xl.order.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.xl.customer.service.IXlCustomerInfoService;
import org.jeecg.modules.xl.order.dto.XlCustomerOrdeDTO;
import org.jeecg.modules.xl.order.dto.XlCustomerShipmentDTO;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.entity.XlCustomerOrderDetail;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.order.service.IXlCustomerOrderDetailService;
import org.jeecg.modules.xl.order.utils.DictUtils;
import org.jeecg.modules.xl.order.vo.*;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecg.modules.xl.store.service.IXlCustomerMystoreService;
import org.jeecg.modules.xl.store.service.IXlCustomerStoreInfoService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: xl_customer_order
 * @Author: jeecg-boot
 * @Date:   2024-10-20
 * @Version: V1.0
 */
@Api(tags="支付审核")
@RestController
@RequestMapping("/xl/payment")
@Slf4j
public class OrdePaymentController {
	@Autowired
	private IXlCustomerOrdeService xlCustomerOrdeService;
	@Autowired
	private IXlCustomerOrderDetailService xlCustomerOrderDetailService;
	 @Autowired
	 private IXlCustomerInfoService xlCustomerInfoService;

	 @Autowired
	 private DictUtils dictUtils;

	 @Autowired
	 private IXlCustomerStoreInfoService xlCustomerStoreInfoService;

	 @Autowired
	 private IXlCustomerMystoreService xlCustomerMystoreService;

	/**
	 * 分页列表查询
	 *
	 * @param xlCustomerOrde
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="支付审核-支付凭证提交", notes="获取 支付审核-支付凭证提交 的记录")
	@GetMapping(value = "/listproofrecord")
	public Result<IPage<XlCustomerOrde>> queryPageList(XlCustomerOrde xlCustomerOrde,
								   //页面类型 (1:订单审核(审核中),2:订单审核(已审核),3:支付审批(凭证上传中),4:支付审批(已审核),
													   // 5:发货管理(发货中),6:发货管理(已发货),7:发货管理(凭证上传中),8:发货管理(已发货),9:支付审批(支付中),10:发货管理(发货中)
								   @RequestParam(name="pageType",required = false) Integer pageType,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("storeCode", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<XlCustomerOrde> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerOrde, req.getParameterMap(),customeRuleMap);
		Page<XlCustomerOrde> page = new Page<XlCustomerOrde>(pageNo, pageSize);

		int ShengHeZhong_Kuaidi = 1;//审核中-快递订单
		int YiShenHe = 2;//已审核
		int Zhifupinzhengtijiao = 3;//支付凭证提交
		int FaHuoZhongPage = 6;//发货中


		if (pageType != null && pageType > 0){
			queryWrapper.lambda()

					//1 是订单审核中 页面的 快递订单 页签对应的条件 ，城配订单另外方法查询
					.and(pageType == ShengHeZhong_Kuaidi, e-> e.eq(XlCustomerOrde::getAuditState, dictUtils.getDictValue("audit_state","待审核"))
							//默认查询为快递的
							.eq(XlCustomerOrde::getDeliveryWay, dictUtils.getDictValue("delivery_way","快递"))
					)
					//2 是订单已审核 页面
					.and(pageType == YiShenHe , e-> e.in(XlCustomerOrde::getAuditState, Arrays.asList( dictUtils.getDictValue("audit_state","审核通过"), dictUtils.getDictValue("audit_state","审核不通过")))
									//默认查询为快递的
									//.eq(XlCustomerOrde::getDeliveryWay, dictUtils.getDictValue("delivery_way","快递"))
					)
					.and(pageType == 3, e-> e.eq(XlCustomerOrde::getAuditState, dictUtils.getDictValue("audit_state","审核通过"))
							//过滤 未提交支付凭证的
							.and(pageType == 3, e2-> e2.isNull(XlCustomerOrde::getPaymentState)
							)
					)
					.eq(pageType == 4,XlCustomerOrde::getPaymentState, dictUtils.getDictValue("payment_state","支付中"))
					.eq(pageType == 5,XlCustomerOrde::getPaymentState, dictUtils.getDictValue("payment_state","已支付"))
					.eq(pageType == FaHuoZhongPage , XlCustomerOrde::getShipmentState, dictUtils.getDictValue("shipment_state","未发货"))


			;
		}else{
			//查询未提交的，状态是-1
			queryWrapper.lambda().eq(XlCustomerOrde::getAuditState, dictUtils.getDictValue("audit_state","待提交"));
		}

		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//当前用户的角色
		String roles = user.getRoleCode();

		//是否管理员角色
//		if (!StrUtil.containsAny(roles, CommonConstant.ADMIN_ROLES)) {
		if (StrUtil.containsAny(roles, "slt_customer")) {//是否是采购人员
			queryWrapper.lambda()
					//筛选自己创建的
					.and(e-> e.eq(XlCustomerOrde::getCreateBy, user.getUsername())
					);
		}

		IPage<XlCustomerOrde> pageList = xlCustomerOrdeService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 城配列表查询
	 * @param city
	 * @param orderCode
	 * @param req
	 * @return
	 */
	@ApiOperation(value="城配列表查询", notes="城配列表查询")
	@GetMapping(value = "/cityList")
	public Result<List<XlCustomerOrdeCityVO>> cityList(
													   @RequestParam(name="city", required = false) String city,
													   @RequestParam(name="orderCode", required = false) String orderCode,
													   HttpServletRequest req) {
		return Result.OK(xlCustomerOrdeService.queryCityList(city, orderCode));
	}

	/**
	 * 城配订单列表查询
	 * @param city
	 * @param req
	 * @return
	 */
	@ApiOperation(value="城配订单列表查询", notes="城配订单列表查询")
	@GetMapping(value = "/cityOrderList")
	public Result<List<XlCustomerOrde>> cityOrderList(@RequestParam(name="city") String city,
												  HttpServletRequest req) {
		List list= xlCustomerOrdeService.list(Wrappers.lambdaQuery(XlCustomerOrde.class)
				.eq(XlCustomerOrde::getDeliveryWay, dictUtils.getDictValue("delivery_way","城配"))
				.eq(XlCustomerOrde::getAuditState, dictUtils.getDictValue("audit_state","待审核"))
				.eq(XlCustomerOrde::getCity, city)
		);
		return Result.OK(list);
	}


	/**
	 * 订单查询
	 * @param xlCustomerOrde
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="订单查询", notes="订单查询")
	@GetMapping(value = "/queryList")
	public Result<IPage<XlCustomerOrdeVO>> queryList(XlCustomerOrde xlCustomerOrde,
													   @RequestParam(name="storeName",required = false) String storeName,
													   @RequestParam(name="createUserName",required = false) String createUserName,
													   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													   HttpServletRequest req) {
		QueryWrapper<XlCustomerOrde> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerOrde, req.getParameterMap());
		Page<XlCustomerOrde> page = new Page<XlCustomerOrde>(pageNo, pageSize);

		//自定义模糊查询
		if (StringUtils.isNotBlank(storeName)){
			queryWrapper.like("storeName",storeName);
		}
		if (StringUtils.isNotBlank(createUserName)){
			queryWrapper.like("createUserName",createUserName);
		}

		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//当前用户的角色
		String roles = user.getRoleCode();

		//是否管理员角色
//		if (!StrUtil.containsAny(roles, CommonConstant.ADMIN_ROLES)) {
		if (StrUtil.containsAny(roles, "slt_customer")) {//是否是采购人员
			queryWrapper.lambda()
					//筛选自己创建的
					.and(e-> e.eq(XlCustomerOrde::getCreateBy, user.getUsername())
					);
		}

		IPage<XlCustomerOrdeVO> pageList = xlCustomerOrdeService.queryList(page, queryWrapper);
		return Result.OK(pageList);
	}


	 /**
	  * 门店信息-通过订单的id查询
	  * @param orderId
	  * @return
	  */
	 @ApiOperation(value="门店信息-通过订单的id查询", notes="门店信息-通过订单的id查询")
	 @GetMapping(value = "/getStoreInfoByOrderId")
	 public Result<XlCustomerStoreInfo> getStoreInfoByOrderId(@RequestParam(name="orderId",required=true) String orderId) {
		 XlCustomerStoreInfo storeInfo = xlCustomerStoreInfoService.getOne(Wrappers.lambdaQuery(XlCustomerStoreInfo.class)
				 .eq(XlCustomerStoreInfo::getIsDeleted, 0)	//未删除的
				 .exists("select 1 from xl_customer_orde t2 where t2.store_code = xl_customer_store_info.store_code and t2.id = {0} ",orderId)
		 );
		 if(storeInfo==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(storeInfo);
	 }

	/**
	 *   添加
	 *
	 * @param xlCustomerOrdePage
	 * @return
	 */
	@AutoLog(value = "xl_customer_order-添加")
	@ApiOperation(value="xl_customer_order-添加", notes="xl_customer_order-添加")
    @RequiresPermissions("lx:xl_customer_orde:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody XlCustomerOrdePage xlCustomerOrdePage) {
		XlCustomerOrde xlCustomerOrde = new XlCustomerOrde();
//		String orderCode =  "CG" + RandomUtil.randomNumbers(13);	//编号生成
		BeanUtils.copyProperties(xlCustomerOrdePage, xlCustomerOrde);
//		xlCustomerOrde.setOrderCode(orderCode);
		xlCustomerOrdeService.saveMain(xlCustomerOrde, xlCustomerOrdePage.getXlCustomerOrderDetailList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param xlCustomerOrdePage
	 * @return
	 */
	@AutoLog(value = "xl_customer_order-编辑")
	@ApiOperation(value="xl_customer_order-编辑", notes="xl_customer_order-编辑")
    @RequiresPermissions("lx:xl_customer_orde:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody XlCustomerOrdePage xlCustomerOrdePage) {
		XlCustomerOrde xlCustomerOrde = new XlCustomerOrde();
		BeanUtils.copyProperties(xlCustomerOrdePage, xlCustomerOrde);
		XlCustomerOrde xlCustomerOrdeEntity = xlCustomerOrdeService.getById(xlCustomerOrde.getId());
		if(xlCustomerOrdeEntity==null) {
			return Result.error("未找到对应数据");
			//已审核的不能编辑
		}else if (xlCustomerOrdeEntity.getAuditState() != null && xlCustomerOrdeEntity.getAuditState().equals("1")){
			return Result.error("已审核的订单不能编辑");

		}
		xlCustomerOrdeService.updateMain(xlCustomerOrde, xlCustomerOrdePage.getXlCustomerOrderDetailList());
		return Result.OK("编辑成功!");
	}


	/**
	 *  订单提交
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "订单提交")
	@ApiOperation(value="订单提交", notes="订单提交")
	@RequiresPermissions("lx:xl_customer_orde:submit")
	@RequestMapping(value = "/submit", method = {RequestMethod.POST})
	public Result<String> submit(@Valid @RequestBody XlCustomerOrdeDTO dto) {
		xlCustomerOrdeService.submit(dto);
		return Result.OK("提交成功!");
	}

	 /**
	  *  订单审核
	  * @param dto
	  * @return
	  */
	 @AutoLog(value = "xl_customer_order-订单审核")
	 @ApiOperation(value="xl_customer_order-订单审核", notes="xl_customer_order-订单审核")
	 @RequiresPermissions("lx:xl_customer_orde:audit")
	 @RequestMapping(value = "/audit", method = {RequestMethod.POST})
	 public Result<String> audit(@RequestBody XlCustomerOrdeDTO dto) {
		 xlCustomerOrdeService.audit(dto);
		 return Result.OK("审核成功!");
	 }


	/**
	 *  支付凭证提交
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "xl_customer_order-支付凭证提交")
	@ApiOperation(value="xl_customer_order-支付凭证提交", notes="xl_customer_order-支付凭证提交")
	@RequiresPermissions("lx:xl_customer_orde:submitPayment")
	@RequestMapping(value = "/submitPayment", method = {RequestMethod.POST})
	public Result<String> submitPayment(@Valid @RequestBody XlCustomerOrdeDTO dto) {
		if (StringUtils.isBlank(dto.getImage())){
			return Result.error("凭证图片不能为空！！");
		}
		xlCustomerOrdeService.submitPayment(dto);
		return Result.OK("提交成功!");
	}

	 /**
	  *  支付确认
	  * @param dto
	  * @return
	  */
	 @AutoLog(value = "xl_customer_order-支付确认")
	 @ApiOperation(value="xl_customer_order-支付确认", notes="xl_customer_order-支付确认")
	 @RequiresPermissions("lx:xl_customer_orde:payment")
	 @RequestMapping(value = "/payment", method = {RequestMethod.POST})
	 public Result<String> payment(@Valid @RequestBody XlCustomerOrdeDTO dto) {
		 xlCustomerOrdeService.payment(dto);
		 return Result.OK("确认成功!");
	 }

	/**
	 *  一键代发
	 * @param id
	 * @return
	 */
	@AutoLog(value = "一键代发")
	@ApiOperation(value="一键代发", notes="一键代发")
	@RequiresPermissions("lx:xl_customer_orde:shiftDelivery")
	@RequestMapping(value = "/shiftDelivery", method = {RequestMethod.POST})
	public Result<String> shiftDelivery(String id) {
		//城配转为快递
		xlCustomerOrdeService.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
			.set(XlCustomerOrde::getDeliveryWay, dictUtils.getDictValue("delivery_way","快递"))
				.eq(XlCustomerOrde::getId, id)
		);
		return Result.OK("代发成功!");
	}



	 /**
	  *  城配发货
	  * @param city
	  * @return
	  */
	 @AutoLog(value = "城配发货")
	 @ApiOperation(value="城配发货", notes="城配发货")
//	 @RequiresPermissions("lx:xl_customer_orde:cityShipment")
	 @RequestMapping(value = "/cityShipment", method = {RequestMethod.POST})
	 public Result<String> cityShipment(String city) {
		 xlCustomerOrdeService.cityShipment(city);
		 return Result.OK("发货成功!");
	 }


	/**
	 *  发货确认
	 * @param dto
	 * @return
	 */
	@AutoLog(value = "xl_customer_order-发货确认")
	@ApiOperation(value="xl_customer_order-发货确认", notes="xl_customer_order-发货确认")
	@RequiresPermissions("lx:xl_customer_orde:shipment")
	@RequestMapping(value = "/shipment", method = {RequestMethod.POST})
	public Result<String> shipment(@Valid @RequestBody XlCustomerShipmentDTO dto) {
		xlCustomerOrdeService.shipment(dto);
		return Result.OK("确认成功!");
	}

	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "xl_customer_order-通过id删除")
	@ApiOperation(value="xl_customer_order-通过id删除", notes="xl_customer_order-通过id删除")
    @RequiresPermissions("lx:xl_customer_orde:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		xlCustomerOrdeService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "xl_customer_order-批量删除")
	@ApiOperation(value="xl_customer_order-批量删除", notes="xl_customer_order-批量删除")
    @RequiresPermissions("lx:xl_customer_orde:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.xlCustomerOrdeService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "xl_customer_order-通过id查询")
	@ApiOperation(value="xl_customer_order-通过id查询", notes="xl_customer_order-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<XlCustomerOrde> queryById(@RequestParam(name="id",required=true) String id) {
		XlCustomerOrde xlCustomerOrde = xlCustomerOrdeService.getById(id);
		if(xlCustomerOrde==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(xlCustomerOrde);
	}


	/**
	 * 通过code查询
	 * @param orderCode
	 * @return
	 */
	@ApiOperation(value="xl_customer_order-通过code查询", notes="xl_customer_order-通过code查询")
	@GetMapping(value = "/queryByCode")
	public Result<XlCustomerOrde> queryByCode(@RequestParam(name="orderCode",required=true) String orderCode) {
		XlCustomerOrde xlCustomerOrde = xlCustomerOrdeService.getOne(Wrappers.lambdaQuery(XlCustomerOrde.class)
			.eq(XlCustomerOrde::getOrderCode, orderCode)
				.last("limit 1 ")
		);
		if(xlCustomerOrde==null) {
			return Result.error("未找到对应订单数据");
		}
		return Result.OK(xlCustomerOrde);
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "xl_customer_order_detail通过主表ID查询")
	@ApiOperation(value="xl_customer_order_detail主表ID查询", notes="xl_customer_order_detail-通主表ID查询")
	@GetMapping(value = "/queryXlCustomerOrderDetailByMainId")
	public Result<List<XlCustomerOrderDetail>> queryXlCustomerOrderDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<XlCustomerOrderDetail> xlCustomerOrderDetailList = xlCustomerOrderDetailService.selectByMainId(id);
		return Result.OK(xlCustomerOrderDetailList);
	}



	/**
	 * 订单商品未发货明细 通过id查询
	 * @param id
	 * @return
	 */
	@ApiOperation(value="订单商品未发货明细", notes="订单商品未发货明细-通主表ID查询")
	@GetMapping(value = "/queryOrderDetailNotShipmentById")
	public Result<List<XlCustomerOrderDetail>> queryOrderDetailNotShipmentById(@RequestParam(name="id",required=true) String id) {
		List<XlCustomerOrderDetail> xlCustomerOrderDetailList = xlCustomerOrderDetailService.queryOrderDetailNotShipmentById(id);
		return Result.OK(xlCustomerOrderDetailList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param xlCustomerOrde
    */
    @RequiresPermissions("lx:xl_customer_orde:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XlCustomerOrde xlCustomerOrde) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<XlCustomerOrde> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerOrde, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<XlCustomerOrde> xlCustomerOrdeList = xlCustomerOrdeService.list(queryWrapper);

      // Step.3 组装pageList
      List<XlCustomerOrdePage> pageList = new ArrayList<XlCustomerOrdePage>();
      for (XlCustomerOrde main : xlCustomerOrdeList) {
          XlCustomerOrdePage vo = new XlCustomerOrdePage();
          BeanUtils.copyProperties(main, vo);
          List<XlCustomerOrderDetail> xlCustomerOrderDetailList = xlCustomerOrderDetailService.selectByMainId(main.getId());
          vo.setXlCustomerOrderDetailList(xlCustomerOrderDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "xl_customer_order列表");
      mv.addObject(NormalExcelConstants.CLASS, XlCustomerOrdePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("xl_customer_order数据", "导出人:"+sysUser.getRealname(), "xl_customer_order"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("lx:xl_customer_orde:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setSheetNum(1);	//只导入一个sheet数据
          params.setStartSheetIndex(0);	//从第一个sheet开始导入
          params.setNeedSave(false);
          try {
              List<OrderSheet> list = ExcelImportUtil.importExcel(file.getInputStream(), OrderSheet.class, params);
			  //根据门店编码进行分组
			  Map<String, List<OrderSheet>> groupedByName = list.stream()
					  .collect(Collectors.groupingBy(OrderSheet::getStoreCode));

			  //处理分组结果，每个分组就是一个订单
              for (Map.Entry<String, List<OrderSheet>> entry : groupedByName.entrySet()) {
				  XlCustomerOrde po = new XlCustomerOrde();
				  List<OrderSheet> orderSheetList = entry.getValue();//这是每一个分组list，相当于一个订单
				  OrderSheet orderSheet = orderSheetList.get(0) ;//因为主表是重复了，所以第一行作为主表信息
				  BeanUtils.copyProperties(orderSheet, po);

				  String store_code = orderSheet.getStoreCode();
				  //查询门店信息
				  XlCustomerStoreInfo targetStore = xlCustomerStoreInfoService.getOne(Wrappers.lambdaQuery(XlCustomerStoreInfo.class)
								  .eq(XlCustomerStoreInfo::getStoreCode , store_code)
				  );
				  if(ObjectUtil.isNull(targetStore)){
					  return Result.error("门店信息有误，请核实:"+store_code);
				  }
//				  String orderCode =  "CG" + RandomUtil.randomNumbers(13);
//				  po.setOrderCode(orderCode);
				  po.setStoreName(targetStore.getStoreName());
				  po.setProvince(targetStore.getProvince());
				  po.setCity(targetStore.getCity());
				  po.setDistrict(targetStore.getDistrict());
				  po.setReceiptZone(targetStore.getProvince()+targetStore.getCity()+targetStore.getDistrict());
				  po.setReceiptAddress(targetStore.getStoreAddress());
				  po.setDeliveryType(targetStore.getDeliveryType());
				  po.setDeliveryWay(targetStore.getDeliveryWay());
				  //门店表里里维护了负责人信息，可以直接取
				  po.setReceiptName(targetStore.getStoreManager());
				  po.setReceiptPhone(targetStore.getStoreManagerPhone());
				  //查询门店人员，随便一个作为收货人
//				  List<XlCustomerMystore> storepoeple = xlCustomerMystoreService.selectByMainId(targetStore.getStoreCode());
//				  if(ObjectUtil.isNotEmpty(storepoeple)){
//					  po.setReceiptName(storepoeple.get(0).getUserName());
//					  po.setReceiptPhone(storepoeple.get(0).getPhone());
//				  }else{
//					  po.setReceiptName("该门店未维护负责人，请核实");
//					  po.setReceiptPhone("");
//				  }
				  //处理订单明细
				  //遍历xlProductInfoPages，取每一个picslist的明细数据，构建picslist
				  List<OrderSheetDetail> orderDetail= new ArrayList<>();
				  for (int i  =0;i<orderSheetList.size();i++){
					  OrderSheetDetail tmp = new OrderSheetDetail();
					  BeanUtils.copyProperties(orderSheetList.get(i).getOrderDetail().get(0),tmp);//每一行就是一个订单明细，只有1行明细，合并起来就是这个订单的所有明细
					  orderDetail.add(tmp);
				  }
                  xlCustomerOrdeService.saveOrderSheetMain(po, orderDetail ,targetStore.getStoreLevel());
              }

              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

	 /**
	  * 导出excel
	  *
	  * @param request
	  */
	 @Autowired
	 private ISysDepartService sysDepartService;
	 @Autowired
	 private IXlProductInfoService productInfoService;
	 @RequiresPermissions("xl:xl_customer_orde:downloadTemplateXls")
	 @RequestMapping(value = "/downloadTemplateXls")
	 public ModelAndView downloadTemplateXls(HttpServletRequest request) {
//		 // Step.1 组装查询条件查询数据
//		 QueryWrapper<XlCustomerOrde> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerOrde, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 //当前用户的角色
		 String roles = sysUser.getRoleCode();

		 boolean isAdmin =false;
		 String [] s = {"slt_admin","admin"};
		 if(StrUtil.containsAny(roles,s)){
			 isAdmin = true;
		 }



		 //log.info("当前登录人的角色是{}, 组织机构/客户有{}, 客户门店有{}个",roles,departNames,storeInfos.size());

		 //组装sheet
		 //多个map，对应了多个sheet
		 List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		 ExportParams orderSheetParams = new ExportParams("订单导入模版", "导入人:" + sysUser.getRealname(),"订单导入模版");
		 orderSheetParams.setType(ExcelType.XSSF);
		 Map<String, Object> orderSheet = new HashMap<>();
		 orderSheet.put(NormalExcelConstants.CLASS, OrderSheet.class);
		 orderSheet.put(NormalExcelConstants.PARAMS, orderSheetParams);

		 OrderSheet orderSheetDataTemp = new OrderSheet();
		 orderSheetDataTemp.setOrderCode("CG2349814124435");
		 orderSheetDataTemp.setStoreCode("MD304573");
		 orderSheetDataTemp.setOrderNotes("示例数据，导入时请删除这个订单");

		 List orderDetaillist   = new ArrayList<OrderSheetDetail>();
		 for(int i = 0;i<5;i++){
			 OrderSheetDetail temp = new OrderSheetDetail();
			 temp.setProductId("示例数据-"+RandomUtil.randomNumbers(8));
			 orderDetaillist.add(temp);
		 }
		 orderSheetDataTemp.setOrderDetail(orderDetaillist);

		 List orderSheetLisst   = new ArrayList<OrderSheet>();
		 orderSheetLisst.add(orderSheetDataTemp);

		 orderSheet.put(NormalExcelConstants.DATA_LIST, orderSheetLisst);
		 listMap.add(orderSheet);

		 //构造门店清单sheet
		 List<XlCustomerStoreInfo> storeList  = new ArrayList<>();
		 if(isAdmin){
			 //如果是管理员或作其他需要查询全部门店的账户，就直接返回全部门店
			 storeList.addAll(xlCustomerStoreInfoService.list());
		 }else{
			 //查询我的门店
			 //QueryWrapper<XlCustomerStoreInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerStoreInfo, req.getParameterMap());
			 QueryWrapper<XlCustomerStoreInfo> queryWrapper =new QueryWrapper<>();
			 queryWrapper.eq("user_account", sysUser.getUsername());
			 storeList.addAll(xlCustomerMystoreService.selectStoresByUserId2(queryWrapper));
		 }

		 Map<String, Object> storeSheet = new HashMap<String, Object>();
		 ExportParams storeSheetParams = new ExportParams("门店清单","门店清单",ExcelType.XSSF);
		 storeSheet.put(NormalExcelConstants.CLASS, XlCustomerStoreInfo.class);
		 storeSheet.put(NormalExcelConstants.PARAMS, storeSheetParams);
		 //导出登录人名下的所有门店ID
		 storeSheet.put(NormalExcelConstants.DATA_LIST, storeList);
		 listMap.add(storeSheet);

		 //商品清单

		 Map<String, Object> productSheet = new HashMap<String, Object>();
		 ExportParams productSheetparam = new ExportParams("商品清单","商品清单",ExcelType.XSSF);
		 productSheet.put(NormalExcelConstants.CLASS, ProductSheet.class);
		 productSheet.put(NormalExcelConstants.PARAMS, productSheetparam);
		 //导出系统之所有的商品清单
		List productList = new ArrayList();
		 if(isAdmin) {
			 //如果是管理员或作其他二线角色要导出模版，那价格为空
			 productList.addAll(productInfoService.getProductListForExport());
		 }else{
			 String price_level =  "三批";//默认三批价格
			 if(ObjectUtil.isNotEmpty(storeList)){
				 price_level = storeList.get(0).getStoreLevel();
			 }
			 //如果是采购人员，那所辖的门店价格等级都是一样的，随便取一个门店的store_level去查询既可
			 productList.addAll(productInfoService.getProductWithPriceListByStoreLevel(price_level));
		 }
		 productSheet.put(NormalExcelConstants.DATA_LIST, productList);
		 listMap.add(productSheet);

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 // Step.4 AutoPoi 导出Excel
		 mv.addObject(NormalExcelConstants.FILE_NAME, "订单导入模版");
		 mv.addObject(NormalExcelConstants.MAP_LIST,listMap);
		 return mv;
	 }

	@ApiOperation(value="订单导出", notes="订单导出")
	@GetMapping(value = "/exportOrder")
	public ModelAndView exportOrder(
			OrderExport orderExport,
			@RequestParam(name="pageType",required = false) Integer pageType,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {

		// 自定义查询规则
		Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
		// 自定义多选的查询规则为：LIKE_WITH_OR
		//customeRuleMap.put("storeCode", QueryRuleEnum.LIKE);
		//customeRuleMap.put("storeName", QueryRuleEnum.LIKE);
		//customeRuleMap.put("createBy", QueryRuleEnum.LIKE);
		//customeRuleMap.put("deliveryCodes", QueryRuleEnum.IN);
		//customeRuleMap.put("createTime", QueryRuleEnum.RANGE);
		Map<String,String[]> getParamete = req.getParameterMap();
		QueryWrapper<OrderExport> queryWrapper = QueryGenerator.initQueryWrapper(orderExport, req.getParameterMap(),customeRuleMap);
		Page<OrderExport> page = new Page<OrderExport>(pageNo, pageSize);

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//当前用户的角色
		String roles = sysUser.getRoleCode();

		//配置当前人员查询条件
		if (StrUtil.containsAny(roles, "slt_customer")) {//是否是采购人员
			queryWrapper.eq("create_by", sysUser.getUsername());
		}
		//配置选中数据查询条件selects[0][id] -> {String[1]@26921} ["185415525179431..."]
		String selections = req.getParameter("selections");
		if(oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("orderCode",selectionList);
		}
		List<OrderExport> s = xlCustomerOrdeService.exportOrderDetailS( queryWrapper);

		//组装sheet
		//多个map，对应了多个sheet
		List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();

		ExportParams orderSheetParams = new ExportParams("订单", "导出人:" + sysUser.getRealname(),"订单清单");
		orderSheetParams.setType(ExcelType.XSSF);
		Map<String, Object> orderSheetMap = new HashMap<>();
		orderSheetMap.put(NormalExcelConstants.CLASS, OrderExport.class);
		orderSheetMap.put(NormalExcelConstants.PARAMS, orderSheetParams);
		orderSheetMap.put(NormalExcelConstants.DATA_LIST, s);


		listMap.add(orderSheetMap);
		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		// Step.4 AutoPoi 导出Excel
		mv.addObject(NormalExcelConstants.FILE_NAME, "订单导出");
		mv.addObject(NormalExcelConstants.MAP_LIST,listMap);
		return mv;

	}

	/**
	 * 订单查询
	 * @param xlCustomerOrde
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="订单查询", notes="订单查询")
	@GetMapping(value = "/queryOrderList2")
	public Result<IPage<XlCustomerOrde>> queryOrderList2(XlCustomerOrde xlCustomerOrde,
													   //页面类型 (1:订单审核(审核中),2:订单审核(已审核),3:支付审批(凭证上传中),4:支付审批(已审核),
													   // 5:发货管理(发货中),6:发货管理(已发货),7:发货管理(凭证上传中),8:发货管理(已发货),9:支付审批(支付中),10:发货管理(发货中)
													   @RequestParam(name="pageType",required = false) Integer pageType,
													   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													   HttpServletRequest req) {
		// 自定义查询规则
		Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
		QueryWrapper<XlCustomerOrde> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerOrde, req.getParameterMap(),customeRuleMap);
		Page<XlCustomerOrde> page = new Page<XlCustomerOrde>(pageNo, pageSize);
		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//当前用户的角色
		String roles = user.getRoleCode();

		if (StrUtil.containsAny(roles, "slt_customer")) {//是否是采购人员
			queryWrapper.lambda()
					//筛选自己创建的
					.and(e-> e.eq(XlCustomerOrde::getCreateBy, user.getUsername())
					);
		}

		IPage<XlCustomerOrde> pageList = xlCustomerOrdeService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *  发货确认
	 * @param dto
	 * @return
	 */
	@ApiOperation(value="复制新建", notes="复制新建")
	@RequestMapping(value = "/copyToCreate", method = {RequestMethod.POST})
	public Result<String> copyToCreate(@Valid @RequestBody XlCustomerOrdeDTO dto) {
		xlCustomerOrdeService.copyToCreate(dto);
		return Result.OK("复制新建成功!");
	}


}
